package com.design.twords.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipException;


/**
 * Create by Alen
 * Time:  1:18
 */
public class FileUtil {
    private static String dir;
    private static String TAG = "FileUtil";

    public FileUtil(Context context) {
       dir = context.getFilesDir().toString();
    }
    //将bitmap写入到文件中 返回文件名
    public static String saveBitmapFile(Bitmap bitmap) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-mm-ss");
        String filename = simpleDateFormat.format(date);
        File file = new File(FileUtil.dir,filename);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return FileUtil.dir+"/"+filename;

    }
    public static byte[] bitmapCompress(Bitmap bitmap, int size) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int quality = 100;
        //循环判断如果压缩后图片是否大于100kb,大于继续压缩,这里的要求数值可根据需求设置
        while (baos.toByteArray().length / 1024 > size) {
            //重置baos即清空baos
            baos.reset();
            //这里压缩quality%，把压缩后的数据存放到baos中
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            if (quality - 10 <= 0)
                break;
            else
                quality -= 10;//每次都减少10
        }
        //转为字节数组返回
        byte[] bytes = baos.toByteArray();
        return bytes;
    }
    // 读取本地文件
    public static String readLocalJson(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        File file = new File(fileName);
        // 文件不存在
        if (!file.exists()) {
            return null;
        }
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String s = stringBuilder.toString().replace("{\"wordRank\"", ",{\"wordRank\"");
        return "[" + s.substring(1) + "]";
    }

    /**
     * @param archive       解压文件的路径
     * @param decompressDir 解压到哪
     * @param isDelete   解压完毕是否删除解压文件
     * @throws IOException
     */
    public static void unZipFile(String archive, String decompressDir, boolean isDelete){
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(archive);
            //获取压缩对象
            for(Enumeration<ZipEntry> enumeration = zipFile.getEntries(); enumeration.hasMoreElements();){
                ZipEntry zipEntry = enumeration.nextElement();
                Log.i("tag","正在解压文件"+zipEntry.getName());
                //如果文件夹不是空的  进行解压
                if(zipEntry.isDirectory()){
                    String path = decompressDir +"/"+ zipEntry.getName();
                    File file = new File(path);
                    if(!file.exists()){
                        file.mkdirs();
                    }

                } else {
                    File file = new File(decompressDir);
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    String path = decompressDir + "/" + zipEntry.getName();
                    File file1 = new File(path);
                    Log.i("tag","正在解压文件"+path);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file1));
                    BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
                    byte [] buf = new byte[1024];
                    int len = 0;
                    while ((len = bis.read(buf)) != -1){
                        bos.write(buf,0,len);
                        bos.flush();
                    }
                    bis.close();
                    bos.close();

                }
            }
        } catch (ZipException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(isDelete){
            File file = new File(archive);
            if (file.exists() && file.getName().endsWith(".zip")) {
                file.delete();
            }
        }
    }

    public static String readFileToString(String filePath, String fileName) {
        FileInputStream inputStream = null;
        BufferedReader reader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            inputStream = new FileInputStream(new File(filePath + "/" + fileName));
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception e) {

        } finally {
            if (reader!=null){
                try {
                    reader.close();
                } catch (IOException e){

                }
            }
        }
        return stringBuilder.toString();
    }


    //将Byte数组转换成文件
    public static void BytesToFile(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists()) {// 判断文件目录是否存在
                Log.d(TAG, "没有这个目录");
                dir.mkdirs();
            }
            file = new File(filePath + "//" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    // 将保存字符串到本地文件
    public static void saveStringToFile(String content, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists()) {// 判断文件目录是否存在
                Log.d(TAG, "没有这个目录");
                dir.mkdirs();
            }
            file = new File(filePath + "//" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(content.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    // 查询文件是否存在
    public static boolean fileIsExit(String filePath, String fileName) {
        File file = new File(filePath + fileName);
        if (file.exists())
            return true;
        else
            return false;
    }

    // 查找目录下所有文件
    public static String[] allFilesInOne(String filePath) {
        File file = new File(filePath);
        return file.list();
    }

}
